package org.hit.burkun.umls.relation;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;
import org.hit.burkun.umls.GeneralQuery;
import org.hit.burkun.umls.relation.UniformRelation.TYPE;

public class OmimRelationAdpater {
	// go-go, go-gene,各种evidence
	public static void main(String[] args) {

		Collection<UniformRelation> res1 = getOmim2GeneRel();
		UniformRelationDump.dumpRelationsWithoutPrimaryId(res1, false,
				"birelation");
	}

	public static Collection<UniformRelation> getOmim2GeneRel() {
		// query do 2 gene
		DBHelper dbh = DBHelper.getLocalBioSearch();
		dbh.connectionDB();
		Collection<String[]> rawRes = dbh.queryData(
				"select disease_omim, gene_id from omim_disease_gene", 2);
		dbh.disconnection();
		HashSet<String> terms1 = new HashSet<String>();
		HashSet<String> terms2 = new HashSet<String>();

		for (String[] line : rawRes) {
			terms1.add(line[0]);
			terms2.add(line[1]);
		}
		// not update unmpapped
		GeneralQuery gq = new GeneralQuery(DBHelper.getServerData(),
				"map_umls_ids", false);
		gq.begin();
		gq.quickMap(terms1, Entity.TYPE.OMIM);
		gq.quickMap(terms2, Entity.TYPE.GENE_ID);
		gq.end();
		Map<String, Set<String>> mapRes = gq.getResult();
		Collection<UniformRelation> res = new LinkedList<UniformRelation>();
		for (String[] line : rawRes) {
			// if umls1 in ontology filter then add, otherwise, just ignor;
			if (mapRes.containsKey(line[0]) && mapRes.containsKey(line[1])) {
				Set<String> umls1 = mapRes.get(line[0]); // ke
				Set<String> umls2 = mapRes.get(line[1]);
				// filter
				boolean isContain = OntologySiddUmlsFilter.isContain(umls1);
				if (isContain) {
					String u1 = StringUtils.join(umls1, ",");
					String u2 = StringUtils.join(umls2, ",");
					Entity ent1 = new Entity(null, null, u1, line[0],
							Entity.TYPE.DISEASE);
					Entity ent2 = new Entity(null, null, u2, line[1],
							Entity.TYPE.GENE_ID);
					UniformRelation ur = new UniformRelation(ent1, ent2, false,
							TYPE.OMIM_GENE);
					res.add(ur);
				}
			}
		}
		return res;
	}

}
